import router from 'umi/router';
import {
  signInService,
  signUpService,
} from '@/services/api';
import { messErr } from '@/utils/message';

export default {
  namespace: 'login',

  state: {
    haveSignIn: false,
    token: '',
    username: '',
  },

  effects: {
    * signInEffect({ payload: { data } }, { call, put }) {
      console.log('登录的数据  => ', data);
      const response = yield call(signInService, data);

      if (response && response.success && response.data) {
        // 登录成功之后的操作
        const data = response.data;
        yield put({
          type: 'signInReducer',
          payload: {
            haveSignIn: true,
            token: data.token,
            username: data.username,
          },
        });
        router.push({
          pathname: '/',
        });
      } else {
        // 登录失败之后，提示用户用户名或密码错误
        messErr(response.err_msg);
      }
    },
    * signUpEffect({ payload: { data } }, { call, put }) {
      console.log('注册的数据  => ', data);
      const response = yield call(signUpService, data);

      if (response && response.success && response.data) {
        // 注册成功之后的操作
        const data = response.data;
        yield put({
          type: 'signInReducer',
          payload: {
            haveSignIn: true,
            token: data.token,
            username: data.username,
          },
        });
        router.push({
          pathname: '/',
        });
      } else {
        // 登录失败之后，提示用户用户名或密码错误
        messErr(response.err_msg);
      }
    },
  },

  reducers: {
    signInReducer(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
